/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package app;

import java.io.*;
import java.util.*;


public class Asker {
    private static String[] DEFAULT_QUESTION = new String[] { "Pytanie testowe, napisz \"odpowiedź\":", "odpowiedź" };
    private Random rand;
    private String path;
    private boolean loaded = false;
    private List<String[]> questions;
    
    
    public Asker(String path, boolean load) {
        this.path = path;
        rand = new Random();
        questions = new ArrayList<>();
        
        if (load) {
            loadFromFile();
        }
    }
    
    public Asker(String path) {
        this(path, true);
    }
    
    
    public void loadFromFile() {
        if (loaded) {
            return;
        }
        
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(path));
            String line;
            
            while ((line = reader.readLine()) != null) {
                addQuestion(line);
            }
            
            loaded = true;
        }
        catch (Exception e) {
            System.err.println("Błąd podczas ładowania pliku z pytaniami.");
        }
        finally {
            if (reader != null) {
                try {
                    reader.close();
                }
                catch (Exception e) {
                    System.err.println("Błąd podczas zamykania pliku z pytaniami.");
                }
            }
        }
    }
    
    private void addQuestion(String line) {
        if (!line.matches(".*?/\\*/.*")) {
            return;
        }
        
        String[] splits = line.split("/\\*/");
        
        if (splits.length == 2) {
            questions.add(new String[] { splits[0].trim(), splits[1].trim() });
        }
    }
    
    public String[] getNextQuestion() {
        int size = questions.size();
        if (size == 0) {
            return DEFAULT_QUESTION;
        }
        
        int idx = rand.nextInt(size);
        return questions.get(idx);
    }
}
